//
//  DWCustomPlayerViewController.m
//  StudyPay
//
//  Created by TopSageOSX on 14-8-19.
//  Copyright (c) 2014年 com.topsage. All rights reserved.
//

#import "DWCustomPlayerViewController.h"
#import "YLAppDelegate.h"
#import "DWCustomPlayerView.h"
#import "GetNetworkStatues.h"
#import "EquipmentInFHeader.h"
#import <AVFoundation/AVFoundation.h>

enum{
    MenuHidenOrShow,
    MenuOutOrIn
};
typedef NSInteger MenuAnimationType;
@interface DWCustomPlayerViewController ()<changeRateProtocol>
/**
 *  主要的播放器
 */
@property (nonatomic,strong)DWMoviePlayerController *player;
//播放器覆盖视图
@property (strong, nonatomic)UIView *overlayView;
//播放器背景视图
@property (strong, nonatomic)UIView *videoBackgroundView;
/**
 *  主计时器，主要的更新操作，包括进度条，时间等等
 */
@property (strong, nonatomic)NSTimer *mainTimer;


//视频状态标签
@property (strong, nonatomic)NSDictionary *playUrls;
@property (strong, nonatomic)NSDictionary *currentPlayUrl;
//清晰度数组
@property (strong, nonatomic)NSArray *qualityDescription;
//当前清晰度
@property (strong, nonatomic)NSString *currentQuality;
@end

@implementation DWCustomPlayerViewController{
    /**
     *  播放器的菜单视图
     */
    DWCustomPlayerView *menuview;
    /**
     *  播放状态标记
     */
    BOOL play;
    /**
     *  隐藏时间，为0隐藏
     */
    int hideTime;
    /**
     *  声音标记
     */
    CGFloat volumeFlag;
    CGFloat volumeFlagValue;
    //原声音
    CGFloat volumeOrder;
    BOOL volumeChange;
    /**
     *  进度标记
     */
    CGFloat progressFlag;
    CGFloat progressFlagValue;
    //原进度
    CGFloat progressSlider;
    BOOL progressChange;
    
    //标记切换
    BOOL exchangeVideo;
    //记录已经播放时间（切换画质用）
    NSInteger hadPlayTime;
    //视频的id，标记视频，保存播放时间用
    NSString *videoID;
    //时间，上次播放的
    double playedtime;
    //id标签
    UILabel *idLabel;
    NSTimer *idTimer;
    MenuAnimationType menuanimationtype;
}
#pragma mark - 初始化以及创建、退出和准备
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change1) name:@"change1" object:nil];
        _qualityDescription = @[@"普通", @"清晰", @"高清"];
        _currentQuality = [_qualityDescription objectAtIndex:0];
    }
    return self;
}
/**
 *  改变画质
 */
-(void)change1{
    [self.player pause];
    [self showOrHidenMenuView];
    menuview.noteLabel.text = @"暂停";
    menuview.noteLabel.hidden=NO;
    play = NO;
    [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_play_media"] forState:UIControlStateNormal];
    if (isPad) {
        [menuview.playBtn setImage:[UIImage imageNamed:@"ic_play_media"] forState:UIControlStateNormal];
    }
    
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
/**
 *  调整屏幕方向
 */
- (void)doForceScreenRotate
{
    
}
- (BOOL)shouldAutorotate{
    return YES;
}
- (BOOL)prefersStatusBarHidden{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
- (void)viewDidLoad
{
    menuanimationtype = MenuHidenOrShow;
    volumeChange = YES;
    
    //FIXME:忽略静音
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [super viewDidLoad];
    //根据是否加密（drm）来初始化
    logdebug(@"DRM:%d",self.drm);
    if (!self.drm) {
        logdebug(@"非加密");
        _player = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID_FREE key:DWACCOUNT_APIKEY_FREE];
        
    }else{
        logdebug(@"加密");
        _player = [[DWMoviePlayerController alloc]initWithUserId:DWACCOUNT_USERID key:DWACCOUNT_APIKEY];
        
    }
    logdebug(@"player:%@",_player);
    //设置Drm端口
    self.player.drmServerPort = ((YLAppDelegate *)[[UIApplication sharedApplication]delegate]).drmServer.listenPort;
    //默认横向
    [self doForceScreenRotate];
    
    //隐藏导航栏
    self.navigationController.navigationBarHidden = YES;
    
    // 加载所需视图
    // 加载播放器 必须第一个加载
    [self loadPlayer];
    // 加载播放器覆盖视图，它作为所有空间的父视图。
    self.overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.overlayView.backgroundColor = [UIColor clearColor];
    //创建状态标签
    menuview.noteLabel.text = @"加载中...";
    hideTime=100;
    CGRect frame = CGRectZero;
    if (IsIOS7) {
        frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        frame = self.view.bounds;
    } else {
        frame = CGRectMake(-20, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
    self.overlayView.frame = frame;
    //    self.overlayView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.overlayView];
    
    
    if (self.videoId) {
        // 获取videoId的播放url
        [self loadPlayUrls];
        
    } else if (self.videoLocalPath) {
        // 播放本地视频
        [self playLocalVideo];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"没有可以播放的视频"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
    
    [self creatMenuView];
}
//创建菜单视图
-(void)creatMenuView{
    //创建
    menuview = [[DWCustomPlayerView alloc]initWithFrame:RECT(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    menuview.delegate = self;
    [menuview.backBtn addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:menuview];
    //标题
    menuview.videoTitle.text = self.videoName;
    //清晰度
    if (self.videoLocalPath) {
        //本地视频，不创建清晰高清切换，本地视频全部为高清
        
        [menuview.qualityBtn setTitle:@"高清" forState:UIControlStateNormal];
        //        menuview.qualityBtn.enabled = NO;
        [menuview.qualityBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        menuview.qualityBtn.backgroundColor = [UIColor clearColor];
        
        [menuview.questionBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [menuview.qualityBtn removeFromSuperview];
        [menuview.questionBtn removeFromSuperview];
    }else{
        [menuview.qualityBtn addTarget:self action:@selector(theQualityOfVideo) forControlEvents:UIControlEventTouchUpInside];
        menuview.questionBtn.hidden=YES;
        [menuview.questionBtn addTarget:self action:@selector(askQuestion) forControlEvents:UIControlEventTouchUpInside];
        [menuview.closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [menuview.finishBtn addTarget:self action:@selector(finishBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    [menuview.favoriteBtn addTarget:self action:@selector(addFavorites:) forControlEvents:UIControlEventTouchUpInside];
    //播放钮
    [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
    if (isPad) {
        [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
    }
    [menuview.playBtn addTarget:self action:@selector(pauseOrPlayVideo) forControlEvents:UIControlEventTouchUpInside];
    [menuview.nextBtn addTarget:self action:@selector(nextVideo) forControlEvents:UIControlEventTouchUpInside];
    [menuview.passBtn addTarget:self action:@selector(passVideo) forControlEvents:UIControlEventTouchUpInside];
    //进度条
    [menuview.progressSlider addTarget:self action:@selector(sliderHadDrog:) forControlEvents:UIControlEventValueChanged];
    [menuview.progressSlider addTarget:self action:@selector(sliderEndDrag:) forControlEvents:UIControlEventTouchUpInside];
    [menuview.progressSlider addTarget:self action:@selector(sliderEndDrag:) forControlEvents:UIControlEventTouchUpOutside];
    //音量
    [menuview.volumeSlider addTarget:self action:@selector(volumeHadDrog:) forControlEvents:UIControlEventValueChanged];
    [menuview.volumeSlider addTarget:self action:@selector(volumeHadDrog:) forControlEvents:UIControlEventTouchUpInside];
    [menuview.volumeSlider addTarget:self action:@selector(volumeHadDrog:) forControlEvents:UIControlEventTouchUpOutside];
    menuview.volumeSlider.value = [MPMusicPlayerController applicationMusicPlayer].volume;
    [menuview.volumeBtn addTarget:self action:@selector(muteOrVolume:) forControlEvents:UIControlEventTouchUpInside];
    //速度
    [menuview.videoRate addTarget:self action:@selector(videoRate:) forControlEvents:UIControlEventTouchUpInside];
    
    
    exchangeVideo = YES;
    self.mainTimer = [[NSTimer alloc]init];
    self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(mainTimerHandler) userInfo:nil repeats:YES];
    hideTime = 100;
    //创建id计时器
    idTimer = [[NSTimer alloc]init];
    idTimer = [NSTimer scheduledTimerWithTimeInterval:34 target:self selector:@selector(showIdLabel) userInfo:nil repeats:YES];
    
    //控制手势
    //单击显示或者隐藏
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showOrHidenMenuView)];
    tap.numberOfTapsRequired = 1;
    //双击播放或者暂停
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pauseOrPlayVideo)];
    doubleTap.numberOfTapsRequired = 2;
    //滑动音量进度控制
    UIPanGestureRecognizer *voiceAndProgressPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(VoiceAndProgress:)];
    //双击失败才判断是单击
    [tap requireGestureRecognizerToFail:doubleTap];
    
    [menuview.gestureView addGestureRecognizer:tap];
    [menuview.gestureView addGestureRecognizer:doubleTap];
    [menuview.gestureView addGestureRecognizer:voiceAndProgressPan];
    
    UILongPressGestureRecognizer * longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpress)];
    longpress.numberOfTouchesRequired = 2;
    longpress.minimumPressDuration = 10;
    [menuview.gestureView addGestureRecognizer:longpress];
    
    //防盗标记
    //    [self addSign];
    //注册通知
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    // MPMoviePlayerLoadStateDidChangeNotification
    [notificationCenter addObserver:self selector:@selector(moviePlayerLoadStateDidChange) name:MPMoviePlayerLoadStateDidChangeNotification object:self.player];
    
    // MPMoviePlayerPlaybackDidFinishNotification
    [notificationCenter addObserver:self selector:@selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.player];
    //转屏通知
    [notificationCenter addObserver:self selector:@selector(oritentationchange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    
    
}
//使用通知转屏
- (void)oritentationchange:(NSNotification *)notification{
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    logdebug(@"%ld",orientation);
    //调整大小位置
    CGFloat height = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
    CGFloat width = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_WIDTH:SCREEN_HEIGHT;
    self.overlayView.frame = CGRectMake(0, 0, height, width);
    self.videoBackgroundView.frame = self.overlayView.frame;
    self.player.view.frame = self.videoBackgroundView.frame;
    if (orientation == UIDeviceOrientationPortrait) {
        //竖屏的时候强制
        logdebug(@"竖向的");
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
    }
    
    
}
/**
 *  加载播放器
 */
- (void)loadPlayer
{
    CGRect frame = CGRectZero;
    
    frame = self.view.frame;
    if (IsIOS7) {
        frame.origin.x = 0;
        frame.origin.y = 0;
        
    } else {
        frame.size.height += 20; //加上状态栏的高度
    }
    //背景
    self.videoBackgroundView = [[UIView alloc] initWithFrame:frame];
    self.videoBackgroundView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.videoBackgroundView];
    
    self.player.scalingMode = MPMovieScalingModeAspectFit;
    self.player.controlStyle = MPMovieControlStyleNone;
    self.player.view.backgroundColor = [UIColor clearColor];
    self.player.view.frame = self.videoBackgroundView.bounds;
    
    [self.videoBackgroundView addSubview:self.player.view];
}
/**
 *  视图将要消失的时候调用
 */
- (void)viewWillDisappear:(BOOL)animated
{
    /**
     *  NOTE: 顺序必须为：
     *      调整屏幕方向 -> 显示 状态栏 -> 显示 navigationController
     *  否则返回播放列表页面时，导航栏的尺寸会发生变化。
     */
    
    // 调整屏幕方向
    //    self.view.transform = CGAffineTransformMakeRotation(-M_PI/2);
    
    // 显示 状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [[UIDevice currentDevice]
     setValue:[NSNumber
               numberWithInteger:UIInterfaceOrientationPortraitUpsideDown]
     forKey:@"orientation"];
    
    // 显示 navigationController
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
/**
 *  视图将要显示的时候调用
 */
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication]
     setStatusBarOrientation:UIInterfaceOrientationPortrait
     animated:NO];
    //    [[UIDevice currentDevice]
    //     setValue:[NSNumber
    //               numberWithInteger:UIInterfaceOrientationLandscapeRight]
    //     forKey:@"orientation"];
}
/**
 *  返回按钮
 */
-(void)backToLastView{
    //记录当前的播放时间
    if (self.player.currentPlaybackTime == self.player.duration) {
        //
        [LocalTime saveTheTime:0 withVideoID:videoID];
    }else{
        [LocalTime saveTheTime:self.player.currentPlaybackTime withVideoID:videoID];
    }
    self.player.fullscreen = NO;
    [self.mainTimer invalidate];
    self.mainTimer = nil;
    [idTimer invalidate];
    idTimer = nil;
    //全部清理掉
    menuview = nil;
    [self.player cancelRequestPlayInfo];
    self.player.contentURL = nil;
    
    [self.player stop];
    self.player.initialPlaybackTime = -1;
    [self.player.view removeFromSuperview];
    self.player = nil;
    self.overlayView = nil;
    self.videoBackgroundView = nil;
    //注销通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    //退出
    if (self.tem == 2) {
        self.playerReturn(self.index.section *1000+self.index.row);
    }else{
        self.playerReturn(_nowVideo);
    }
    
    if (IsIOS8) {
        [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait];
    }else{
        [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 播放在线/本地
/**
 *  播放在线视频
 */
- (void)loadPlayUrls
{
    logdebug(@"在线");
    self.player.videoId = self.videoId;
    videoID = self.videoId;
    [self performSelector:@selector(showFavoite) withObject:nil afterDelay:1];
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:REMEMBER_LAST]isEqualToString:@"NO"]) {
        //直接播放
    }else{
        //继续上次播放
        self.player.initialPlaybackTime = [LocalTime getThePlayedTimeWithVideoID:videoID];
    }
    //超时时间，20，···网卡的话···呵呵，其实还不如不看
    self.player.timeoutSeconds = 20;
    
    __block DWCustomPlayerViewController *blockSelf = self;
    self.player.failBlock = ^(NSError *error) {
        logdebug(@"error: %@", [error localizedDescription]);
        //TODO:跳出或重置
        //失败的话也得置NO
        exchangeVideo = NO;
    };
    //获取播放的地址
    self.player.getPlayUrlsBlock = ^(NSDictionary *playUrls) {
        // [必须]判断 status 的状态，不为"0"说明该视频不可播放，可能正处于转码、审核等状态。
        NSNumber *status = [playUrls objectForKey:@"status"];
        //显示不可播放的原因
        if (status == nil || [status integerValue] != 0) {
            NSString *message = [NSString stringWithFormat:@"%@ %@:%@",
                                 blockSelf.videoId,
                                 [playUrls objectForKey:@"status"],
                                 [playUrls objectForKey:@"statusinfo"]];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        blockSelf.playUrls = playUrls;
        [blockSelf resetViewContent];
    };
    
    [self.player startRequestPlayInfo];
    play = YES;
}
-(void)longpress{
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 60, 20)];
    label.textColor = [UIColor whiteColor];
    [label setText:@"zzz"];
    label.alpha = 0.1;
    [self.view addSubview:label];
    
    //    sleep(4);
    //    label.hidden = YES;
    
}

/**
 *  根据播放url更新涉及的视图
 */
- (void)resetViewContent
{
    
    //默认高清
    // 获取默认清晰度播放url
    NSNumber *defaultquality = [self.playUrls objectForKey:@"defaultquality"];
    int i = 0;
    for (NSDictionary *playurl in [self.playUrls objectForKey:@"qualities"]) {
        if (defaultquality == [playurl objectForKey:@"quality"]) {
            self.currentPlayUrl = playurl;
        }
        //增加画质按钮和状态
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setTitle:[playurl objectForKey:@"desp"] forState:UIControlStateNormal];
        [btn setTintColor:RGBCOLOR(160, 160, 160)];
        btn.tag = [[playurl objectForKey:@"quality"]integerValue];
        if (isPad) {
            btn.frame = RECT(0, i*45, 90, 40);
            btn.titleLabel.font = FONT_BOLD_BIG;
        }else{
            btn.frame = RECT(0, i*35, 50, 30);
            btn.titleLabel.font = FONT(15);
        }
        [btn addTarget:self action:@selector(selectQuality:) forControlEvents:UIControlEventTouchUpInside];
        [menuview.ztyQualityView addSubview:btn];
        //默认选择
        if (i==0) {
            btn.selected = YES;
        }
        i++;
    }
    //没有的话就第一个吧，通常都是越来越高清
    if (!self.currentPlayUrl) {
        self.currentPlayUrl = [[self.playUrls objectForKey:@"qualities"] objectAtIndex:0];
    }
    
    [self.player prepareToPlay];
    [self.player play];
}
/**
 *  重置播放器
 */
- (void)resetPlayer
{
    self.player.contentURL = [NSURL URLWithString:[self.currentPlayUrl objectForKey:@"playurl"]];
    //跳转已经播放的时间
    self.player.initialPlaybackTime = hadPlayTime;
    self.player.currentPlaybackTime = hadPlayTime;
    menuview.noteLabel.hidden = NO;
    menuview.noteLabel.text = @"切换中...";
    [self.player prepareToPlay];
    [self.player play];
}



/**
 *  播放本地文件
 */
- (void)playLocalVideo
{
    self.playUrls = [NSDictionary dictionaryWithObject:self.videoLocalPath forKey:@"playurl"];
    //保存ID
    NSArray *array = [self.videoLocalPath componentsSeparatedByString:@"/"];
    NSString *s = [array lastObject];
    NSArray *array1 = [s componentsSeparatedByString:@"."];
    videoID = [array1 firstObject];
    [self performSelector:@selector(showFavoite) withObject:nil afterDelay:1];
    //跳转本地保存时间
    //    self.player.currentPlaybackTime = [LocalTime getThePlayedTimeWithVideoID:videoID];
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:REMEMBER_LAST]isEqualToString:@"NO"]) {
        //直接播放
    }else{
        //继续上次播放
        self.player.initialPlaybackTime = [LocalTime getThePlayedTimeWithVideoID:videoID];
    }
    
    logdebug(@"本地%@",self.playUrls);
    logdebug(@"player%@",self.player);
    //本地没有画质可选
    menuview.qualityBtn.hidden = YES;
    //    menuview.qualityView.hidden = YES;
    menuview.ztyQualityView.hidden = YES;
    self.player.contentURL = [[NSURL alloc] initFileURLWithPath:self.videoLocalPath];
    
    [self.player prepareToPlay];
    [self.player play];
    play = YES;
}


/**
 *  获取下一个视频的信息(为了记录学习进度)
 */
-(void)getNextVideoInfoWithTem:(NSInteger)tem andDic:(NSDictionary *)dic{
    hideTime = 15;
    if (self.tem==0) {
        //视图视频的请求
        logdebug(@"试听界面下一讲");
        ListenTestModel *model = dic;
        logdebug(@"%@",model);
        NSString *idString = [NSString stringWithFormat:@"%@",model.videoId];
        NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
        NSString *string = [NSString stringWithFormat:@"/OpenCourse/videoDetail/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
        NSString *MD5string = [string md5];
        NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/OpenCourse/videoDetail/hash/%@/appid/1", MD5string];
        //参数
        NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",idString,@"id", nil];
        //POST请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //开始请求
        [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //请求成功
            NSDictionary *infoDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSDictionary *info = [[infoDic objectForKey:@"info"]lastObject];
            NSString *videoIdString = [info objectForKey:@"address"];
            //            NSString *videoName = [NSString stringWithFormat:@"%@",[info objectForKey:@"subjectname"]];
            ListenTestModel *model=[_videoListArray objectAtIndex:_nowVideo];
            //新视频id等赋值
            self.videoId = videoIdString;
            self.videoName = model.title;
            menuview.videoTitle.text = self.videoName;
            //请求新的视频
            [self loadPlayUrls];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //打印错误信息
            _nowVideo--;
            logdebug(@"error:%@",error.localizedDescription);
        }];
    }else if (self.tem==1){
        //访谈界面的请求
        logdebug(@"访谈下一讲");
        InterviewModel *model = dic;
        NSString *idString = [NSString stringWithFormat:@"%@",model.videoId];
        NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
        NSString *string = [NSString stringWithFormat:@"/Interview/videoDetail/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
        NSString *MD5string = [string md5];
        NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/Interview/videoDetail/hash/%@/appid/1", MD5string];
        //参数
        NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",idString,@"id", nil];
        //POST请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //开始请求
        [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //请求成功
            NSDictionary *infoDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSDictionary *info=[[infoDic objectForKey:@"info"]lastObject];
            NSString *videoIdString = [info objectForKey:@"address"];
            NSString *videoName = [info objectForKey:@"title"];
            //重新赋值
            self.videoId = videoIdString;
            self.videoName = videoName;
            menuview.videoTitle.text = self.videoName;
            //请求视频
            [self loadPlayUrls];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //打印错误信息
            _nowVideo--;
            logdebug(@"error:%@",error.localizedDescription);
        }];
    }else{
        //课程界面的请求
        VideoListModel *model = dic;
        NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
        NSString *string = [NSString stringWithFormat:@"/CourseCenter/videoDisplay/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
        NSString *MD5string = [string md5];
        NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/CourseCenter/videoDisplay/hash/%@/appid/1", MD5string];
        
        NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"mid",model.videoId,@"lectureId", nil];
        //请求
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //成功
            NSDictionary *infoDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            NSString *spark = [infoDic objectForKey:@"spark"];
            NSString *drm = [infoDic objectForKey:@"drm"];
            self.videoId = spark;
            if ([drm isEqualToString:@"1"]) {
                //
                self.drm = YES;
            }else{
                self.drm = NO;
            }
            self.videoName = [NSString stringWithFormat:@"%@ %@",[infoDic objectForKey:@"lecture_chapter"],[infoDic objectForKey:@"lecture_section"]];
            menuview.videoTitle.text = self.videoName;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //失败
            _nowVideo--;
            logdebug(@"%@",error.localizedDescription);
        }];
    }
}
/**
 *  主计时器方法
 */
-(void)mainTimerHandler{
    //TODO:计时器方法
    if (exchangeVideo) {
        hideTime = 5;
    }
    /**
     *   判断如果在线的，则继续播放下一讲；如果是本地视频，不继续播放下一讲
     */
    if (menuview.progressSlider.value==1&&self.tem!=3) {
        [self nextVideo];
    }
    //改变进度条和时间指示
    float progress=0;
    if (self.player.duration) {
        progress = self.player.currentPlaybackTime/self.player.duration;
        int cm = (int)self.player.currentPlaybackTime/60;
        int cs = (int)self.player.currentPlaybackTime%60;
        int dm = (int)self.player.duration/60;
        int ds = (int)self.player.duration%60;
        NSString *time = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d",cm,cs,dm,ds];
        menuview.currentProgressTime.text = time;
        //每隔8秒记录当前进度，防止崩溃丢失进度
        if ((int)self.player.currentPlaybackTime%8==0&&self.player.currentPlaybackTime!=0) {
            [LocalTime saveTheTime:self.player.currentPlaybackTime withVideoID:videoID];
        }
    }
    menuview.progressSlider.value = progress;
    if (self.player.playbackState == MPMoviePlaybackStatePlaying) {
        //
        if (![menuview.noteLabel.text isEqualToString:@"加载下一讲"]) {
            menuview.noteLabel.hidden = YES;
        }
        menuview.volume.hidden = YES;
        menuview.schedule.hidden = YES;
    }
    if (menuview.progressSlider.value==1&&!exchangeVideo) {
        
        menuview.noteLabel.text = @"此讲结束";
        menuview.noteLabel.hidden = NO;
        hideTime=20;
    }
    //更改隐藏时间
    if (hideTime>0) {
        hideTime --;
    }
    //为0隐藏菜单界面
    if (hideTime == 0) {
        //渐隐
        if (menuanimationtype == MenuHidenOrShow) {
            [menuview menuHiden];
        }else{
            [menuview menuOut];
        }
    }
    //    [self getCachData];
}
/**
 *  获取下载状态缓存大小
 */
- (void)getCachData{
    NSArray *events = self.player.accessLog.events;
    int count = events.count;
    for (int i = 0; i < count; ++i) {
        MPMovieAccessLogEvent *currenEvent = [events objectAtIndex:i];
        double byts =  currenEvent.indicatedBitrate ;
        int64_t tmp = byts / 8;
        tmp = tmp / 1024;
        int64_t byte = currenEvent.numberOfBytesTransferred;
        int64_t bytes =  currenEvent.numberOfBytesTransferred >> 10;
        if(bytes > 1024)
        {
            bytes = bytes >> 10;
        }
        //        NSLog(@"byts = %f, byte = %lld bytes = %lld bits = %lld", byts,byte, bytes, tmp);
    }
}

#pragma mark - 播放控制与菜单选项
/**
 *  暂停或者播放
 */
-(void)pauseOrPlayVideo{
    logdebug(@"暂停按钮%d",play);
    if (!play) {
        menuview.rateView.hidden = YES;
        //        menuview.ztyrateView.hidden = YES;
        
        [UIView animateWithDuration:0.4 animations:^{
            
            CGRect rect = menuview.ztyrateView.frame;
            
            CGFloat height = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
            
            //            if (rect.origin.x >= height - 56) {
            //                rect.origin.x -= 56;
            //            }else{
            //                rect.origin.x += 56;
            //            }
            rect.origin.x = height;
            menuview.ztyrateView.frame = rect;
            
        }];
        
        
        logdebug(@"继续");
        [self.player play];
        hideTime = 5;
        play = YES;
        menuview.noteLabel.hidden = YES;
        [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
        if (isPad) {
            [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
        }
    }else{
        logdebug(@"暂停");
        [self.player pause];
        play = NO;
        menuview.noteLabel.text = @"暂停";
        menuview.noteLabel.hidden = NO;
        menuview.alpha = 1;
        [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_play_media"] forState:UIControlStateNormal];
        if (isPad) {
            [menuview.playBtn setImage:[UIImage imageNamed:@"ic_play_media"] forState:UIControlStateNormal];
        }
        //暂停之后应该使menuview长时间显示暂停状态
        hideTime = 3000;
    }
    
}
/**
 *  下一讲
 */
- (void)nextVideo{
    logdebug(@"下一讲事件");
    if (self.tem!=3) {
        //调整提示
        hideTime = 10;
        menuview.noteLabel.text = @"加载下一讲";
        menuview.noteLabel.hidden = NO;
        menuview.noteLabel.alpha = 1;
        if (self.tem != 1&&self.tem!=0) {
            //
            logdebug(@"%@",self.index);
            if (!exchangeVideo) {
                _nowVideo++;
                NSInteger row = self.index.row;
                NSInteger sec = self.index.section;
                row++;
                NSDictionary *dic = [self.nextArray objectAtIndex:sec];
                NSArray *array = [dic objectForKey:@"array"];
                if (row>=array.count) {
                    row = 0;
                    sec++;
                    if (sec>=self.nextArray.count) {
                        //最后了，返回
                        [self backToLastView];
                        return;
                    }
                }
                self.index = [NSIndexPath indexPathForItem:row inSection:sec];
                
                [LocalTime saveTheTime:0 withVideoID:videoID];
                exchangeVideo = YES;
                dic = [self.nextArray objectAtIndex:sec];
                array = [dic objectForKey:@"array"];
                
                VideoListModel *model = [array objectAtIndex:row];
                NSString *pcm;
                //不一类就返回吧
                if ([model.drm isEqualToString:@"1"]) {
                    pcm = @"pcm";
                    if (!self.drm) {
                        //
                        [self backToLastView];
                    }
                }else{
                    pcm = @"mp4";
                    if (self.drm) {
                        [self backToLastView];
                    }
                }
                //请求为了记录学习进度
                [self getNextVideoInfoWithTem:self.tem andDic:model];
                //判断是否存在
                if (model.hadlocal) {
                    //本地
                    self.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,model.spark,pcm];
                    logdebug(@"====================\n%@",self.videoLocalPath);
                    [self playLocalVideo];
                }else{
                    //新视频id等赋值
                    self.videoId = model.spark;
                    //                self.videoName = model.section;
                    //                menuview.videoTitle.text = self.videoName;
                    [self loadPlayUrls];
                }
            }
        }else{
            logdebug(@"非课程下一讲");
            if (!exchangeVideo) {
                exchangeVideo = YES;
                _nowVideo++;
                if (_nowVideo>=self.nextArray.count) {
                    //越界返回
                    [self backToLastView];
                }else{
                    [self getNextVideoInfoWithTem:self.tem andDic:[self.nextArray objectAtIndex:_nowVideo]];
                }
            }
            
        }
        
    }
    //改变进度条和时间指示
    float progress=0;
    if (self.player.duration) {
        progress = self.player.currentPlaybackTime/self.player.duration;
        int cm = (int)self.player.currentPlaybackTime/60;
        int cs = (int)self.player.currentPlaybackTime%60;
        int dm = (int)self.player.duration/60;
        int ds = (int)self.player.duration%60;
        NSString *time = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d",cm,cs,dm,ds];
        menuview.currentProgressTime.text = time;
    }
    menuview.progressSlider.value = progress;
}
/**
 *  上一讲
 */
- (void)passVideo{
    logdebug(@"上一讲");
    hideTime = 10;
    if (self.tem!=3) {
        menuview.noteLabel.text = @"加载上一讲";
        menuview.noteLabel.hidden = NO;
        menuview.noteLabel.alpha = 1;
        if (self.tem != 1&&self.tem!=0) {
            //
            if (!exchangeVideo) {
                _nowVideo--;
                NSInteger row = self.index.row;
                NSInteger sec = self.index.section;
                logdebug(@"%@",self.index);
                row--;
                NSDictionary *dic = [self.nextArray objectAtIndex:sec];
                NSArray *array = [dic objectForKey:@"array"];
                if (row<0) {
                    sec--;
                }
                if (sec<0) {
                    //第一个，返回
                    [self backToLastView];
                }else{
                    [LocalTime saveTheTime:0 withVideoID:videoID];
                    exchangeVideo = YES;
                    
                    dic = [self.nextArray objectAtIndex:sec];
                    array = [dic objectForKey:@"array"];
                    if (row<0) {
                        row = array.count-1;
                    }
                    self.index = [NSIndexPath indexPathForItem:row inSection:sec];
                    VideoListModel *model = [array objectAtIndex:row];
                    //不一类就返回吧
                    NSString *pcm;
                    if ([model.drm isEqualToString:@"1"]) {
                        pcm = @"pcm";
                        if (!self.drm) {
                            //
                            [self backToLastView];
                        }
                    }else{
                        pcm = @"mp4";
                        if (self.drm) {
                            [self backToLastView];
                        }
                    }
                    //请求为了记录学习进度
                    [self getNextVideoInfoWithTem:self.tem andDic:model];
                    //判断是否存在
                    if (model.hadlocal) {
                        //本地
                        self.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,model.spark,pcm];
                        self.videoId = nil;
                        [self playLocalVideo];
                    }else{
                        //新视频id等赋值
                        self.videoLocalPath = nil;
                        self.videoId = model.spark;
                        //                self.videoName = model.section;
                        //                menuview.videoTitle.text = self.videoName;
                        [self loadPlayUrls];
                    }
                }
            }
        }else{
            logdebug(@"非课程上一讲");
            if (!exchangeVideo) {
                _nowVideo--;
                if (_nowVideo<0) {
                    //越界返回
                    [self backToLastView];
                }else{
                    [self getNextVideoInfoWithTem:self.tem andDic:[self.nextArray objectAtIndex:_nowVideo]];
                }
            }
        }
        
    }
    //改变进度条和时间指示
    float progress=0;
    if (self.player.duration) {
        progress = self.player.currentPlaybackTime/self.player.duration;
        int cm = (int)self.player.currentPlaybackTime/60;
        int cs = (int)self.player.currentPlaybackTime%60;
        int dm = (int)self.player.duration/60;
        int ds = (int)self.player.duration%60;
        NSString *time = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d",cm,cs,dm,ds];
        menuview.currentProgressTime.text = time;
    }
    menuview.progressSlider.value = progress;
    
}
/**
 *  进度条拖动
 *
 *  @param slider slider
 */
-(void)sliderHadDrog:(UISlider *)slider{
    //拖动的时候暂停视频
    //暂停之后应该停掉maintimer，否则可能会使进度条跳动
    [self.mainTimer setFireDate:[NSDate distantFuture]];
    
    //设置时间栏的时间随滑动而改变
    int current = slider.value*self.player.duration;
    
    int cm = current/60;
    int cs = current%60;
    
    int dm = (int)self.player.duration/60;
    int ds = (int)self.player.duration%60;
    
    NSString *time = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d",cm,cs,dm,ds];
    menuview.currentProgressTime.text = time;
    
    //拖动的时候不隐藏
    hideTime = 5;
}
/**
 *  进度条停止拖动
 *
 *  @param slider slider
 */
-(void)sliderEndDrag:(UISlider *)slider{
    logdebug(@"停止拖动");
    if (slider.value!=1) {
        self.player.currentPlaybackTime = slider.value*self.player.duration;
        if (self.player.playbackState != MPMoviePlaybackStatePlaying) {
            [self.player prepareToPlay];
            [self.player play];
        }
        [self.mainTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    }else{
        [self.mainTimer setFireDate:[NSDate date]];
    }
}
/**
 *  音量拖动
 *
 *  @param slider slider
 */
- (void)volumeHadDrog:(UISlider *)slider{
    hideTime = 5;
    [MPMusicPlayerController applicationMusicPlayer].volume = slider.value;
    //触发静音事件
    if (slider.value == 0) {
        menuview.volumeBtn.selected = YES;
    }else{
        menuview.volumeBtn.selected = NO;
    }
}
/**
 *  音量停止拖动
 *
 *  @param slider slider
 */
- (void)volumeEndDrog:(UISlider *)slider{
    [MPMusicPlayerController applicationMusicPlayer].volume = slider.value;
    if (slider.value == 0) {
        menuview.volumeBtn.selected = YES;
    }else{
        menuview.volumeBtn.selected = NO;
    }
}
/**
 *  静音按钮
 *
 *  @param btn 按钮
 */
- (void)muteOrVolume:(UIButton *)btn{
    if (btn.selected) {
        btn.selected = NO;
        [MPMusicPlayerController applicationMusicPlayer].volume = 0.3;
        menuview.volumeSlider.value = 0.3;
    }else{
        //静音
        btn.selected = YES;
        [MPMusicPlayerController applicationMusicPlayer].volume = 0.0;
        menuview.volumeSlider.value = 0.0;
    }
}

/**
 *  显示或者隐藏菜单视图
 */
-(void)showOrHidenMenuView{
    logdebug(@"menushoworhide");
    if (self.player.playbackState==MPMoviePlaybackStatePlaying) {
        if (hideTime == 0) {
            hideTime = 5;
            if (menuanimationtype == MenuHidenOrShow) {
                [menuview menuShow];
            }else{
                [menuview menuIn];
            }
        }else{
            hideTime = 0;
            if (menuanimationtype == MenuHidenOrShow) {
                [menuview menuHiden];
            }else{
                [menuview menuOut];
            }
        }
        
    }else{
        hideTime = 3000;
        if ([menuview.noteLabel.text isEqualToString:@"跳转中"]) {
            hideTime = 5;
        }
        if (menuanimationtype == MenuHidenOrShow) {
            [menuview menuShow];
        }else{
            [menuview menuIn];
        }
        if (menuview.rateView.hidden == NO){
            menuview.rateView.hidden = YES;
            //            menuview.ztyrateView.hidden = YES;
            [UIView animateWithDuration:0.4 animations:^{
                
                CGRect rect = menuview.ztyrateView.frame;
                CGFloat height = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
                //                if (rect.origin.x >= height - 56) {
                //                    rect.origin.x -= 56;
                //                }else{
                //                    rect.origin.x += 56;
                //                }
                rect.origin.x = height;
                menuview.ztyrateView.frame = rect;
                
            }];
        }
    }
}
/**
 *  音量加减
 *
 *  @param span 滑动
 */
-(void)VoiceAndProgress:(UIPanGestureRecognizer *)pan{
    progressFlag = 0;
    volumeFlag = 0;
    if (ABS([pan translationInView:self.view].y)>ABS([pan translationInView:self.view].x)+5) {
        //确定是调整声音
        progressFlag = 0;
        volumeFlag = 1;
    }
    if (ABS([pan translationInView:self.view].x)>ABS([pan translationInView:self.view].y)+5){
        //确定是调整进度
        volumeFlag = 0;
        progressFlag = 1;
    }
    //获取变化进度
    progressFlagValue = [pan translationInView:self.view].x;
    volumeFlagValue = [pan translationInView:self.view].y;
    CGFloat dragProgress = progressFlagValue/SCREEN_HEIGHT*0.3;
    CGFloat dragVolume = -volumeFlagValue/SCREEN_WIDTH;
    //开始拖动
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        //        logdebug(@"开始滑动");
        //        logdebug(@"%f/%f",
        //                 menuview.progressSlider.value,SCREEN_HEIGHT);
        
        //记录当前进度条位置
        progressSlider = menuview.progressSlider.value;
        //记录当前声音大小
        volumeOrder = [MPMusicPlayerController applicationMusicPlayer].volume;
    }
    /////
    //调整声音
    //
    if (volumeFlag == 1&&volumeChange) {
        logdebug(@"调节音量");
        [MPMusicPlayerController applicationMusicPlayer].volume = volumeOrder+dragVolume;
        menuview.volumeSlider.value = volumeOrder+dragVolume;
        //禁止进度调整
        progressChange = NO;
        //触发静音
        if ([MPMusicPlayerController applicationMusicPlayer].volume == 0.0) {
            menuview.volumeBtn.selected = YES;
        }else{
            menuview.volumeBtn.selected = NO;
        }
    }
    
    ////
    //调整进度
    //
    if (progressFlag == 1&&progressChange) {
        logdebug(@"调节进度");
        //暂停播放器
        [self.player pause];
        //暂停计时器
        [self.mainTimer setFireDate:[NSDate distantFuture]];
        //显示菜单
        if (menuanimationtype == MenuHidenOrShow) {
            [menuview menuShow];
        }else{
            [menuview menuIn];
        }
        hideTime = 3;
        //超出时长计算
        if ((dragProgress+self.player.currentPlaybackTime/self.player.duration)>1) {
            //
            dragProgress = (self.player.duration-self.player.currentPlaybackTime)/self.player.duration;
        }
        menuview.noteLabel.text = [NSString stringWithFormat:@"%@%02d:%02d",dragProgress>0?@"前进":@"后退",(int)ABS(dragProgress*self.player.duration)/60,(int)ABS(dragProgress*self.player.duration)%60];
        menuview.noteLabel.hidden = NO;
        menuview.progressSlider.value = progressSlider+dragProgress;
        //拖动进度的过程中禁止音量变化
        volumeChange = NO;
    }
    if (pan.state ==  UIGestureRecognizerStateEnded) {
        if (progressChange) {
            //继续播放
            logdebug(@"结束滑动");
            play = YES;
            [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
            if (isPad) {
                [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
            }
            self.player.currentPlaybackTime = menuview.progressSlider.value*self.player.duration;
            [self.player play];
            [self.mainTimer setFireDate:[NSDate date]];
            //结束进度的变化时可以调节音量
            volumeChange = YES;
        }
        if (volumeChange) {
            progressChange = YES;
        }
    }
}

/**
 *  播放速度
 *
 *  @param btn btn
 */
-(void)videoRate:(UIButton *)btn{
    CGRect rect2 = menuview.ztyrateView.frame;
    CGFloat height2 = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
    if (menuview.ztyrateView.frame.origin.x > height2 - 56) {
        menuview.rateView.hidden = NO;
        //        menuview.ztyrateView.hidden = NO;
        [UIView animateWithDuration:0.4 animations:^{
            
            CGRect rect = menuview.ztyrateView.frame;
            CGFloat height = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
            //            if (rect.origin.x >= height - 56) {
            //                rect.origin.x -= 56;
            //            }else{
            //                rect.origin.x += 56;
            //            }
            rect.origin.x = height - 56;
            menuview.ztyrateView.frame = rect;
            
        }];
        
        
        
        //        self.myblock();
        
    }else{
        menuview.rateView.hidden = YES;
        //        menuview.ztyrateView.hidden = YES;
        [UIView animateWithDuration:0.4 animations:^{
            
            CGRect rect = menuview.ztyrateView.frame;
            CGFloat height = SCREEN_HEIGHT>SCREEN_WIDTH?SCREEN_HEIGHT:SCREEN_WIDTH;
            //            if (rect.origin.x >= height - 56) {
            //                rect.origin.x -= 56;
            //            }else{
            //                rect.origin.x += 56;
            //            }
            rect.origin.x = height ;
            menuview.ztyrateView.frame = rect;
            
        }];
    }
}
/**
 *  改变播放倍速
 *
 *  @param btn btn
 */
-(void)changeRata:(NSInteger)index{
    
    if (play == NO) {
        logdebug(@"正在播放");
    }else{
        logdebug(@"暂停了");
        [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
        if (isPad) {
            [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
        }
    }
    NSArray *btnArray =
    [menuview.rateView subviews];
    if (index == 0) {
        self.player.currentPlaybackRate = 0.8;
        [menuview.videoRate setTitle:@"0.8X" forState:UIControlStateNormal];
    }else if (index == 1){
        self.player.currentPlaybackRate = 1.0;
        [menuview.videoRate setTitle:@"1.0X" forState:UIControlStateNormal];
    }else if (index == 2){
        self.player.currentPlaybackRate = 1.2;
        [menuview.videoRate setTitle:@"1.2X" forState:UIControlStateNormal];
    }else{
        self.player.currentPlaybackRate = 1.5;
        [menuview.videoRate setTitle:@"1.5X" forState:UIControlStateNormal];
    }
    logdebug(@"%d",play);
    if (play == YES) {
        
    }else{
        [self.player pause];
        
        play = NO;
    }
    for (UIButton *b in btnArray) {
        if (b.tag != index) {
            [b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            b.backgroundColor = [UIColor clearColor];
        }else{
            [b setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            b.backgroundColor = [UIColor lightGrayColor];
        }
    }
    if (play == YES) {
        hideTime = 5;
    }else{
        hideTime = 300;
    }
    
}

- (void)changeVideoRate:(UIButton *)btn{
    if (play == NO) {
        logdebug(@"正在播放");
    }else{
        logdebug(@"暂停了");
        [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
        if (isPad) {
            [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
        }
    }
    NSArray *btnArray =
    [menuview.rateView subviews];
    if (btn.tag == 0) {
        self.player.currentPlaybackRate = 0.8;
        [menuview.videoRate setTitle:@"0.8X" forState:UIControlStateNormal];
    }else if (btn.tag == 1){
        self.player.currentPlaybackRate = 1.0;
        [menuview.videoRate setTitle:@"1.0X" forState:UIControlStateNormal];
    }else if (btn.tag == 2){
        self.player.currentPlaybackRate = 1.2;
        [menuview.videoRate setTitle:@"1.2X" forState:UIControlStateNormal];
    }else{
        self.player.currentPlaybackRate = 1.5;
        [menuview.videoRate setTitle:@"1.5X" forState:UIControlStateNormal];
    }
    logdebug(@"%d",play);
    if (play == YES) {
        
    }else{
        [self.player pause];
        
        play = NO;
    }
    for (UIButton *b in btnArray) {
        if (b.tag != btn.tag) {
            [b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            b.backgroundColor = [UIColor clearColor];
        }else{
            [b setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            b.backgroundColor = [UIColor lightGrayColor];
        }
    }
    if (play == YES) {
        hideTime = 5;
    }else{
        hideTime = 300;
    }
}
/**
 *   提问问题
 */
-(void)askQuestion{
    logdebug(@"提问问题");
    menuview.questionView.hidden = NO;
    logdebug(@"暂停");
    [self.player pause];
    play = NO;
    menuview.noteLabel.text = @"暂停";
    menuview.noteLabel.hidden = NO;
    menuview.alpha = 1;
    [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_play_media"] forState:UIControlStateNormal];
    if (isPad) {
        [menuview.playBtn setImage:[UIImage imageNamed:@"ic_play_media"] forState:UIControlStateNormal];
    }
    //暂停之后应该使menuview长时间显示暂停状态
    hideTime = 3000;
}
-(void)closeBtnClick{
    logdebug(@"关闭");
    menuview.questionView.hidden = YES;
}
-(void)finishBtnClick{
    logdebug(@"提交");
    menuview.questionView.hidden = YES;
}
/**
 *  添加收藏按钮点击事件
 *
 *  @param btn btn
 */
- (void)addFavorites:(UIButton *)btn{
    logdebug(@"favorite:%@",videoID);
    if (btn.selected) {
        btn.selected = NO;
        logdebug(@"移除收藏");
        NSMutableArray *favorits = [NSMutableArray arrayWithContentsOfFile:FAVORITE_PATH];
        int x = 0;
        for (int i = 0; i<favorits.count; i++) {
            if ([[favorits objectAtIndex:i]isEqualToString:videoID]) {
                x = i;
            }
        }
        [favorits removeObjectAtIndex:x];
        [favorits writeToFile:FAVORITE_PATH atomically:YES];
    }else{
        btn.selected = YES;
        logdebug(@"添加收藏");
        NSMutableArray *favorits = [NSMutableArray arrayWithContentsOfFile:FAVORITE_PATH];
        if (favorits) {
            [favorits addObject:[videoID copy]];
        }else{
            favorits = [NSMutableArray array];
            [favorits addObject:[videoID copy]];
        }
        [favorits writeToFile:FAVORITE_PATH atomically:YES];
    }
}
/**
 *  显示是否收藏
 */
- (void)showFavoite{
    NSArray *favorites = [NSArray arrayWithContentsOfFile:FAVORITE_PATH];
    for (NSString *videoid in favorites) {
        if ([videoid isEqualToString:videoID]) {
            logdebug(@"yuuuuuuuuuuuuuuuuuuuu");
            [menuview.favoriteBtn setSelected:YES];
        }
    }
    logdebug(@"FA:%@",favorites);
    logdebug(@"%@",videoID);
}
/**
 *  视频质量
 */
-(void)theQualityOfVideo{
    
    if (menuview.ztyQualityView.hidden) {
        menuview.ztyQualityView.hidden = NO;
    }else{
        menuview.ztyQualityView.hidden = YES;
    }
}
//选择画质
-(void)selectQuality:(UIButton *)btn{
    play = YES;
    [menuview.playBtn setImage:[UIImage imageNamed:@"小窗_stop_media"] forState:UIControlStateNormal];
    if (isPad) {
        [menuview.playBtn setImage:[UIImage imageNamed:@"ic_stop_media"] forState:UIControlStateNormal];
    }
    
    
    for (UIButton *btns in menuview.ztyQualityView.subviews) {
        btns.selected = NO;
    }
    
    btn.selected = YES;
    NSArray *array = [self.playUrls objectForKey:@"qualities"];
    for (int i = 0; i<array.count; i++) {
        NSDictionary *urlDic = [array objectAtIndex:i];
        if (btn.tag == [[urlDic objectForKey:@"quality"]integerValue]) {
            //
            if ([self.currentPlayUrl objectForKey:@"quality"] != [urlDic objectForKey:@"quality"]) {
                self.currentPlayUrl = urlDic;
            }else{
                //一个画质就返回行了
                //之前有判定，这是以防万一
                return;
            }
        }
    }
    //修改当前的清晰度
    [menuview.qualityBtn setTitle:[self.currentPlayUrl objectForKey:@"desp"] forState:UIControlStateNormal];
    menuview.ztyQualityView.hidden = YES;
    
    //记录当前播放时间
    hadPlayTime = self.player.currentPlaybackTime;
    //重置播放器
    [self resetPlayer];
}
/**
 *  改变视频大小，适配或者满屏
 *  ##功能已废弃##
 */
-(void)changeSize{
    //满屏
    if (self.player.scalingMode == MPMovieScalingModeFill) {
        self.player.view.frame = self.videoBackgroundView.bounds;
        self.player.scalingMode = MPMovieScalingModeAspectFit;
    }else{
        self.player.view.frame = self.videoBackgroundView.bounds;
        self.player.scalingMode = MPMovieScalingModeFill;
    }
}

#pragma mark - 版权相关
/**
 *  防盗标记
 */
-(void)addSign{
    //用户id
    idLabel = [[UILabel alloc]init];
    idLabel.backgroundColor = [UIColor clearColor];
    idLabel.text = [UserMessage sharedUserMessage].userMid;
    idLabel.textColor = RGBCOLOR(76, 92, 137);
    idLabel.hidden = YES;
    [self.view addSubview:idLabel];
    
}
/**
 *  显示用户的id以及随机位置
 */
-(void)showIdLabel{
    NSInteger k = self.overlayView.frame.size.width-120;
    NSInteger numb = self.overlayView.frame.size.height-20;
    int y = arc4random()%k;
    int x = arc4random()%numb;
    CGFloat Sy = 20.0f+y;
    CGFloat Sx = x>self.overlayView.bounds.size.height*0.2?x:self.overlayView.bounds.size.height*0.2;
    idLabel.hidden = NO;
    idLabel.frame = CGRectMake(Sy, Sx, 100, 20 );
    [self performSelector:@selector(hideIdLabel) withObject:nil afterDelay:0.8];
}
-(void)hideIdLabel{
    idLabel.hidden = YES;
}
//----------------------------
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //
    logdebug(@"超内存");
    if( self.view.window == nil && [self isViewLoaded]) {
        
        //安全移除控制器的view;
        logdebug(@"内存警告|||||||||警告||||||||||");
        //        [self.player stop];
        [self dismissViewControllerAnimated:NO completion:nil];
        self.view = nil;//[_view release];_view = nil;
        
    }
}
//视频状态改变
#pragma mark - moviePlayerLoadStateDidChange
- (void)moviePlayerLoadStateDidChange
{
    logdebug(@"播放状态改变:%@ playbackState: %ld  %d", self.player.originalContentURL, (long)self.player.playbackState,self.player.drmServerPort);
    //状态改变的时候再置NO，否则可能会比较急，容易出问题
    exchangeVideo = NO;
    switch (self.player.loadState) {
        case MPMovieLoadStatePlayable:
            // 可播放
            logdebug(@"%@ playable", self.player.originalContentURL);
            menuview.noteLabel.text = @"正在加载...";
            [self.player play];
            hideTime = 5;
            break;
            
        case MPMovieLoadStatePlaythroughOK:
            // 状态为缓冲几乎完成，可以连续播放
            logdebug(@"%@ PlaythroughOK", self.player.originalContentURL);
            menuview.noteLabel.text = @"正在加载...";
            //            self.videoStatusLabel.hidden = YES;
            hideTime = 5;
            [self.player play];
            break;
            
        case MPMovieLoadStateStalled:
            // 缓冲中
            logdebug(@"%@ Stalled", self.player.originalContentURL);
            menuview.noteLabel.text = @"正在加载...";
            hideTime = 5;
            [self.player play];
            break;
            
        default:
            break;
    }
    
}
//播放器状态改变
- (void)moviePlayerPlaybackDidFinish:(NSNotification *)notification
{
    logdebug(@"accessLog\n info:%@\n%@", [[NSString alloc]initWithData:self.player.accessLog.extendedLogData encoding:NSUTF8StringEncoding],[self.player.accessLog.events firstObject]);
    logdebug(@"errorLog\n info:\n%@", [[NSString alloc]initWithData:self.player.errorLog.extendedLogData encoding:NSUTF8StringEncoding]);
    NSNumber *n = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
    switch ([n intValue]) {
        case MPMovieFinishReasonPlaybackEnded:
            logdebug(@"PlaybackEnded");
            //            menuview.hidden = YES;
            //播放完成，显示菜单或者
            [menuview menuShow];
            break;
            
        case MPMovieFinishReasonPlaybackError:{
            logdebug(@"PlaybackError");
            menuview.hidden = NO;
            //            ShowAlertMsg(@"此视频出错，请在线观看");
            if (self.videoId) {
                menuview.noteLabel.text =  @"加载失败";
            }else{
                menuview.noteLabel.text =  @"出错，请在线看";
            }
        }
            break;
            
        case MPMovieFinishReasonUserExited:
            logdebug(@"ReasonUserExited");
            break;
            
        default:
            break;
    }
}

/**
 *   点击回收键盘
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [menuview.questionTitleTextFiled resignFirstResponder];
    [menuview.questionTextView resignFirstResponder];
}

@end
